<template>
  <!-- 修改资料 -->

  <div>
    <el-form :model="form" label-position="right" ref="formRef">
      <ts-card header="活动基本信息">
        <el-row :gutter="12">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="名称" required>
              <el-input v-model="promotion.name" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="活动类型" required>
              <el-input
                v-model="promotion.promotionTypeName"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="生效时间">
              <el-date-picker
                v-model="promotion.startDateTime"
                type="datetime"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="YYYY-MM-DD hh:mm:ss"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="截止时间">
              <el-date-picker
                v-model="promotion.endDateTime"
                type="datetime"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="YYYY-MM-DD hh:mm:ss"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </ts-card>
      <ts-card>
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <span>商品列表</span>
            <div style="display:flex">
            <el-button @click="addGood" type="primary">新 增</el-button>
            <el-button @click="deleteGoods" :icon="Delete" type="danger" plain>删 除</el-button>
            </div>
          </div>
        </template>
        <el-table :data="dataList" @selection-change="selectGoods">
            <el-table-column type="selection" width="45"></el-table-column>
          <el-table-column prop="mtlName" label="商品名称"></el-table-column>
          <el-table-column prop="mtlNumber" label="商品编号"></el-table-column>
          <el-table-column prop="mtlKind" label="商品类别"></el-table-column>
          <el-table-column prop="originalPrice" label="原价"></el-table-column>
          <el-table-column prop="stockQty" label="限售总数"></el-table-column>
          <el-table-column
            prop="minPurchaseQty"
            label="至多购买数"
          ></el-table-column>
          <el-table-column
            prop="couponCount"
            label="选中规则数"
          ></el-table-column>
          <el-table-column fixed="right" label="操作" width="60">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editGoods(scope.row)"
                >修 改</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </ts-card>
      <ts-card title="促销商品">
        <el-row :gutter="15">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="商品编号">
              <sc-table-select
                v-model="form"
                fileName="ProductReport"
                :props="productProps"
                :inputWidth="500"
                :mapping="productMapping"
                @change="goodsChange"
              ></sc-table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="商品名称" required>
              <el-input v-model="form.mtlName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="原价" required>
                <el-input v-model="form.originalPrice" disabled/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="至少购买数">
                <el-input-number v-model="form.minPurchaseQty"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="至多购买数">
                <el-input-number v-model="form.maxPurchaseQty"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="限售总数" required>
                <el-input-number v-model="form.stockQty"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="立减与优惠券同时使用" required>
              <el-switch v-model="form.couponAndDeduce"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="能否使用积分" required>
              <el-switch v-model="form.canUsePoints"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="允许超过至多购买数" required>
              <el-switch v-model="form.allowExceedQty "></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否区分SKU" required>
              <el-switch v-model="form.matchSku "></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="优惠规则">
              <sc-table-select
                v-model="couponList"
                fileName="ChooseCouponReport"
                :props="CouponProps"
                multiple
                injectionKey="goods"
                :inputWidth="500"
                :maxCollapseTags="4"
              ></sc-table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                inline-prompt
                active-value="normal"
                inactive-value="disable"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="优惠商品列表">
            <el-table :data="couponList">
            <el-table-column prop="number" label="编号"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="transactionKind" label="业务类型"></el-table-column>
            <el-table-column prop="ruleType" label="规则类型"></el-table-column>
            <el-table-column prop="couponAmount" label="优惠价格"></el-table-column>
            <el-table-column prop="orderMinAmount" label="满价格"></el-table-column>
            <el-table-column prop="useGoodRange" label="适用产品"></el-table-column>
          </el-table>
            </el-form-item>
        </el-col>
        <el-col style="margin-top:20px" v-show="form.matchSku&&skuList.length>0" :span="24">
            <el-form-item label="SKU列表">
            <el-table ref="skuListRef" :data="skuList" @selection-change="selectSKU">
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column prop="mtlSkuName" label="sku名称"></el-table-column>
            <el-table-column prop="originalPrice" label="原价"></el-table-column>
            <el-table-column prop="minPurchaseQty" label="至少购买数">
                <template #default="scope">
                    <el-input-number size="small" style="width: 100%;" v-model="scope.row.minPurchaseQty"/>
                </template>
            </el-table-column>
            <el-table-column prop="maxPurchaseQty" label="至多购买数">
                <template #default="scope">
                    <el-input-number size="small" style="width: 100%;" v-model="scope.row.maxPurchaseQty"/>
                </template>
            </el-table-column>
            <el-table-column prop="stockQty	" label="限售总数">
                <template #default="scope">
                    <el-input-number size="small" style="width: 100%;" v-model="scope.row.stockQty"/>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-switch v-model="scope.row.status" inline-prompt active-value="normal" inactive-value="disable" disabled/>
                </template>
            </el-table-column>
            </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </ts-card>
    </el-form>
    <div class="button-position">
      <el-button @click="updateVisible">退 出</el-button>
      <el-button type="primary" @click="addGoods(formRef)">确 定</el-button>
    </div>
  </div>
</template>
    
    
  <script setup>
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox ,ElNotification} from "element-plus";
import {deepClone} from '@/utils/arr'
import tsEditor from "@/components/scEditor/index.vue";
import Api from "@/api/model/mall";
const emit = defineEmits(["updatetable"]);
const props = defineProps({
  paramsData: {
    type: Object,
    defalut: {},
  },
});
// 添加用户数据的对象
const form = ref({});
const goods = ref({})
const promotion = ref({});
const skuList = ref([])
const selectSKUList = ref([])
const skuListRef = ref(null)
const dataList = ref([]);
const deleteList = ref([])
const couponList = ref([])
const configData = ref({});
const productProps = {
  value: "mtlNumber",
  label: "mtlNumber",
};
const CouponProps = {
  value: "id",
  label: "name",
}
const productMapping = [
  { value: "id", label: "mtlId" },
  { value: "number", label: "mtlNumber" },
  { value: "name", label: "mtlName" },
  { value: "price", label: "originalPrice" },
  { value: "minPurchaseQty", label: "minPurchaseQty" },
  { value: "maxPurchaseQty", label: "maxPurchaseQty" },
];
const formRef = ref(null);
onMounted(() => {
  getInit();
});

const updateVisible = () => {
  emit("updatetable");
};

const getInit = async (val) => {
  let res = await Api.promotion.goods.add.post(props.paramsData);
  console.log(res)
  if (res.code == "200") {
    form.value = deepClone(res.data);
    goods.value = deepClone(res.data)
    promotion.value = res.promotion;
    configData.value = res.configData;
    dataList.value = res.dataList;
  }
};
const selectGoods = (rows)=>{
    deleteList.value = rows
}
const addGood = ()=>{
    getInit()
}
const editGoods = async(val)=>{
    let  res = await Api.promotion.goods.detail.post({id:val.id})
    console.log(res)
  if (res.code == "200") {
    form.value = deepClone(res.data);
    goods.value = deepClone(res.data)
    promotion.value = res.promotion;
    configData.value = res.configData;
    couponList.value = res.couponList
    skuList.value = res.dataList
    skuList.value.forEach((ele)=>{
        if(ele.selected){
            console.log(ele)
            nextTick(()=>{
                skuListRef.value.toggleRowSelection (ele,true);
            })
           
        }
        
    })
  }
}
const deleteGoods = async () => {
  if (deleteList.value.length > 0) {
    let param = {
        rowIds: deleteList.value.map((ele) => {
        return ele.id;
      }),
    };
    ElMessageBox.confirm("确定删除吗？", "提示", {
      type: "warning",
      confirmButtonText: "确定",
      confirmButtonClass: "el-button--danger",
    })
      .then(async() => {
        console.log(param)
        let res =await Api.promotion.goods.delete.post(param);
        if (res.code == 200) {
          ElNotification.success({ message: "删除成功", duration: 2000 });
          getInit()
        }
      })
      .catch(() => {});
  } else {
    ElMessage({
      message: "请选择表格记录",
      type: "warning",
    });
  }
};
const goodsChange = async()=>{
    form.value = Object.assign(deepClone(goods.value),form.value)
    let res = await Api.promotion.goods.queryGoodsSkuList.post({mtlId:form.value.mtlId})
    console.log(res)
    if(res.code == '200'){
        skuList.value = res.dataList
        if(skuList.value.length>0){
            form.value.matchSku = true
        }
    }
}
const selectSKU = (rows)=>{
    selectSKUList.value = rows
//    skuList.value = rows
}
const restAddFormData = () => {
  formRef.value.resetFields();
};

// 上传
const addGoods = async (formRef) => {
  await formRef.validate((valid, fields) => {
    if (valid) {
      addGoodsData();
    }
  });
};

const addGoodsData = async () => {
  form.value.couponIds = couponList.value
    .map((ele) => {
      return ele.id;
    })
    .toString();
  let params = {
    bean: form.value,
    dataList:selectSKUList.value
  };
  console.log(params)
  let res =await Api.promotion.goods.saveOrUpdate.post(params);
  console.log(res)
  if (res.code == '200') {
    restAddFormData();
    ElNotification.success({
      title: "",
      message: "操作成功！",
      duration: 2000,
    });
    couponList.value = []
    skuList.value = []
    selectSKUList.value = []
    getInit()
  }
};
</script>
    
    <style scoped></style>
    
    